﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.AuditLogging.Client.Configuration;
using System.ServiceProcess;
using Microsoft.Win32;
using System.IO;
using PSE.AuditLogging.ContingencyService.Configuration;
using System.Configuration;

namespace PSE.AuditLogging.ContingencyService.Management
{
    public class ConfigurationManager
    {
        private System.Configuration.Configuration _configFile;
        private LogResenderConfigurationSection _masterConfigSection;

        public ConfigurationManager()
        {
            string serviceName = "BM&FBOVESPA Audit Logging Contingency Service";
            string exeFilePath = Convert.ToString(Registry.GetValue(@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\BM&FBOVESPA Audit Logging Contingency Service", "ImagePath", string.Empty));

            exeFilePath = exeFilePath.Replace("\"", "");

            if (!File.Exists(exeFilePath))
                throw new Exception("Error retrieving the service configuration file.");

            _configFile = System.Configuration.ConfigurationManager.OpenExeConfiguration(@exeFilePath);

            _masterConfigSection = _configFile.GetSection(Constants.LOGRESENDER_SECTION_NAME) as LogResenderConfigurationSection;

            if (_masterConfigSection == null)
                throw new Exception("Error retrieving the logResender configuration section.");

        }

        /// <summary>
        /// Configurar o intervalo de execução do componente
        /// </summary>
        /// <param name="executionInterval">Tempo em milisegundos</param>
        public void SetExecutionInterval(int executionInterval)
        {
            if (_masterConfigSection.ExecutionInterval != executionInterval)
            {
                _masterConfigSection.ExecutionInterval = executionInterval;
                _configFile.Save();
            }
        }
        /// <summary>
        /// Recuperar o intervalo de execução configurado
        /// </summary>
        public int GetExecutionInterval()
        {
            return _masterConfigSection.ExecutionInterval;
        }

        /// <summary>
        /// Adicionar ou atualizar(caso já exista) a configuração de um produto
        /// </summary>
        /// <param name="configuration"></param>
        public void AddOrUpdateProduct(LogSenderConfigurationSection configuration)
        {
            //caso nao exista, adicionar
            if (_masterConfigSection.LogSenders[configuration.ProductId] == null)
                _masterConfigSection.LogSenders.Add(configuration);
            else
                _masterConfigSection.LogSenders[configuration.ProductId] = configuration;

            _configFile.Save();
        }

        /// <summary>
        /// Remover a configuração de um produto
        /// </summary>
        /// <param name="productId"></param>
        public void RemoveProduct(string productId)
        {
            //caso nao exista, adicionar
            if (_masterConfigSection.LogSenders[productId] != null)
            {
                _masterConfigSection.LogSenders.Remove(productId);
                _configFile.Save();
            }
        }

        /// <summary>
        /// Recuperar a configuração de um produto
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public LogSenderConfigurationSection GetProductConfiguration(string productId)
        {
            return _masterConfigSection.LogSenders[productId];
        }

        /// <summary>
        /// Recuperar todas as configurações de produtos
        /// </summary>
        /// <returns></returns>
        public List<LogSenderConfigurationSection> GetProductsConfigurations()
        {
            List<LogSenderConfigurationSection> ret = new List<LogSenderConfigurationSection>();
            foreach (LogSenderConfigurationSection item in _masterConfigSection.LogSenders)
            {
                ret.Add(item);
            }

            return ret;
        }

        public List<string> GetConfiguredProducts()
        {
            List<string> ret = new List<string>();
            foreach (LogSenderConfigurationSection item in _masterConfigSection.LogSenders)
            {
                ret.Add(item.ProductId);
            }

            return ret;
        }
    }
}
